package com.goldfish666.remote_control.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
// 统计工具
public class StatisticsHelper {

    public boolean allInputAccept(Map<List<Byte>, Integer> countMap, int accept) {
        for (List<Byte> key : countMap.keySet()) {
            if (countMap.get(key) <= accept) {
                return false;
            }
        }
        return true;
    }

    public boolean canDivide(Map<List<Byte>, Integer> countMap, int length, int accept, double reduceRate, double enhanceRate) {
        if (countMap.size() == length && allInputAccept(countMap, accept)) {
            return true;
        }
        if (countMap.values().size() < length) {
            return false;
        }
        List<Integer> indexs = new ArrayList<>(countMap.values());
        indexs.sort((o1, o2) -> o2 - o1);
        int lastPointIndex = getLastPointIndex(indexs);
        double rate = getRate(indexs);

        if (lastPointIndex >= length - 1 && rate > enhanceRate || lastPointIndex <= length - 1 && rate > reduceRate) {
            return true;
        }

        return false;
    }

    public double getRate(List<Integer> list) {
        double rate = 0.0;
        for (int i = 0; i < list.size() - 1; i++) {
            double currentRate = 1.0 * list.get(i) / list.get(i + 1);
            if (currentRate > rate) {
                rate = currentRate;
            }
        }
        return rate;
    }

    public int getLastPointIndex(List<Integer> list) {
        double rate = 0.0;
        int result = 0;

        for (int i = 0; i < list.size() - 1; i++) {
            double currentRate = 1.0 * list.get(i) / list.get(i + 1);
            if (currentRate > rate) {
                rate = currentRate;
                result = i;
            }
        }
        return result;
    }

    public int getRepresentativeListLength(Map<List<Byte>, Integer> countMap, int length, int accept) {
        if (allInputAccept(countMap, accept)) {
            return length;
        } else {
            List<Integer> indexs = new ArrayList<>(countMap.values());
            indexs.sort((o1, o2) -> o2 - o1);
            return getLastPointIndex(indexs) + 1;
        }
    }

}
